package com.xindaoapp.happypet;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.bulletnoid.android.widget.StaggeredGridView.StaggeredGridView;
import com.bulletnoid.android.widget.StaggeredGridView.StaggeredGridView.OnLoadmoreListener;
import com.bulletnoid.android.widget.StaggeredGridView.StaggeredGridView.OnScrollListener1;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshStaggeredGridView;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.xindaoapp.happypet.activity.HomeBannerDetailActivity;
import com.xindaoapp.happypet.adapter.HomeListAdapter;
import com.xindaoapp.happypet.adapter.HomeVideoAdapter;
import com.xindaoapp.happypet.adapter.MainNewAdapter;
import com.xindaoapp.happypet.api.AddClient;
import com.xindaoapp.happypet.api.Address;
import com.xindaoapp.happypet.bean.HomeBanner;
import com.xindaoapp.happypet.bean.HomeBannerEntity;
import com.xindaoapp.happypet.bean.HomeData;
import com.xindaoapp.happypet.bean.HomeEntity;
import com.xindaoapp.happypet.bean.HomeVideo;
import com.xindaoapp.happypet.bean.HomeVideo.Video;
import com.xindaoapp.happypet.bean.Message;
import com.xindaoapp.happypet.bean.MyHuiFu;
import com.xindaoapp.happypet.fragment.XDBaseFragment;
import com.xindaoapp.happypet.ui.PostDetailActivity;
import com.xindaoapp.happypet.utils.CommonParameter.UserState;
import com.xindaoapp.happypet.utils.CommonUtil;
import com.xindaoapp.happypet.utils.Constants;
import com.xindaoapp.happypet.utils.SharePrefUtil;
import com.xindaoapp.happypet.utils.xdConfig;
import com.xindaoapp.happypet.view.RollViewPager;

/**
 * 主界面
 * 
 * 
 * @author Administrator
 */
@SuppressLint({"ShowToast", "NewApi"})
public class ClubFragement extends XDBaseFragment implements OnClickListener {
    private RelativeLayout main_leftmenu;
    private ImageButton main_rightmenu;
    private static SlidingMenu menu;
    private static Context context;
    private PullToRefreshStaggeredGridView ptrgv;
    private SharedPreferences sp;

    private LinearLayout top_check;

    private RelativeLayout top_jinghua;
    private RelativeLayout top_new;
    private RelativeLayout top_video;

    private ConnectionChangeReceiver mChangeReceiver;


    /**
     * 右下角 返回顶部按钮
     */
    private ImageView back_top;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.activity_main, null);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        context = getActivity();

        super.onCreate(savedInstanceState);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView();
        menu = ((MainActivity) getActivity()).getSlidingMenu();
        mChangeReceiver = new ConnectionChangeReceiver();
        context.registerReceiver(mChangeReceiver, new IntentFilter(
                "android.net.conn.CONNECTIVITY_CHANGE"));
    }

    /** 轮播图 */
    private LinearLayout mViewPager;
    private TextView tvDescription;
    private LinearLayout llPoints;

    private RelativeLayout club_jinghua;
    private RelativeLayout club_new;
    private RelativeLayout club_video;

    private int currentPage1 = 1;
    private static int currentPage2 = 1;
    private int currentPage3 = 1;

    @SuppressWarnings("static-access")
    private void initView() {
        sp = context.getSharedPreferences("userconfig", context.MODE_PRIVATE);
        main_leftmenu = (RelativeLayout) getView().findViewById(R.id.main_leftmenu);
        main_rightmenu = (ImageButton) getView().findViewById(R.id.main_rightmenu);
        back_top = (ImageView) getView().findViewById(R.id.back_top);
        top_check = (LinearLayout) getView().findViewById(R.id.top_check);
        top_check.setVisibility(View.GONE);
        main_leftmenu.setOnClickListener(this);
        main_rightmenu.setOnClickListener(this);
        back_top.setOnClickListener(this);

        ptrgv = (PullToRefreshStaggeredGridView) getView().findViewById(R.id.ptrgv);
        ptrgv.setMode(PullToRefreshBase.Mode.BOTH);
        ptrgv.getRefreshableView().setColumnCount(2);
        ptrgv.setVisibility(View.GONE);
        LayoutInflater inflater =
                (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View header = inflater.inflate(R.layout.xlistview_viewpage, null);
        View foot = inflater.inflate(R.layout.layout_loading_footer, null);
        club_jinghua = (RelativeLayout) header.findViewById(R.id.club_jinghua);
        club_jinghua.setSelected(true);
        club_new = (RelativeLayout) header.findViewById(R.id.club_new);
        club_video = (RelativeLayout) header.findViewById(R.id.club_video);
        mViewPager = (LinearLayout) header.findViewById(R.id.viewpager1);
        tvDescription = (TextView) header.findViewById(R.id.tv_image_description1);
        llPoints = (LinearLayout) header.findViewById(R.id.ll_points1);

        club_jinghua.setOnClickListener(this);
        club_new.setOnClickListener(this);
        club_video.setOnClickListener(this);

        ptrgv.getRefreshableView().setHeaderView(header);
        ptrgv.getRefreshableView().setFooterView(foot);

        top_jinghua = (RelativeLayout) getView().findViewById(R.id.top_jinghua);
        top_new = (RelativeLayout) getView().findViewById(R.id.top_new);
        top_video = (RelativeLayout) getView().findViewById(R.id.top_video);

        top_jinghua.setOnClickListener(this);
        top_new.setOnClickListener(this);
        top_video.setOnClickListener(this);

        top_jinghua.setSelected(true);

        ptrgv.setOnRefreshListener(new OnRefreshListener<StaggeredGridView>() {
            @Override
            public void onRefresh(PullToRefreshBase<StaggeredGridView> refreshView) {
                if (CommonUtil.isNetworkAvailable(context) == 0) {
                    Toast.makeText(context, "当前网络不可用", Toast.LENGTH_SHORT).show();
                    ptrgv.onRefreshComplete();
                    return;
                }
                getBannerData();
                currentPage1 = 1;
                currentPage2 = 1;
                currentPage3 = 1;
                if (tab == 1) {
                    flag2 = true;
                    getJingData(currentPage1, 0);
                } else if (tab == 2) {
                    flag3 = true;
                    getNewData(currentPage2, 0);
                } else if (tab == 3) {
                    flag4 = true;
                    videoAdapter.getItems().clear();
                    loadVideoData(currentPage3);
                }
                ptrgv.onRefreshComplete();
            }
        });
        ptrgv.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore() {
                if (CommonUtil.isNetworkAvailable(context) == 0) {
                    Toast.makeText(context, "当前网络不可用", Toast.LENGTH_SHORT).show();
                    ptrgv.onRefreshComplete();
                    return;
                }
                if (tab == 1) {
                    currentPage1++;
                    getJingData(currentPage1, 1);
                } else if (tab == 2) {
                    currentPage2++;
                    getNewData(currentPage2, 1);
                } else if (tab == 3) {
                    if (total3 == videoAdapter.getItems().size()) {
                        // Toast.makeText(context, "没有更多数据了", Toast.LENGTH_SHORT).show();
                        // ptrgv.getRefreshableView().getFooterView().setVisibility(View.GONE);
                        return;
                    } else {
                        currentPage3++;
                        loadVideoData(currentPage3);
                    }
                }
            }
        });
        ptrgv.getRefreshableView().setOnScrollListener1(new OnScrollListener1() {
            @Override
            public void onScoll(int first) {
                int top = ptrgv.getRefreshableView().getHeaderView().getTop();
                if (Math.abs(top) >= ptrgv.getRefreshableView().getHeaderView().getHeight()
                        - top_check.getHeight()) {
                    top_check.setVisibility(View.VISIBLE);
                } else {
                    top_check.setVisibility(View.GONE);
                }
                if (Math.abs(top) >= 2000) {
                    back_top.setVisibility(View.VISIBLE);
                } else {
                    back_top.setVisibility(View.GONE);
                }
            }
        });

        getBannerData();
        getJingData(currentPage1, 0);
    }

    /** 获取Banner的数据 */
    private HomeEntity entity;
    private HomeBannerEntity homebanner;
    private final boolean flag = false;
    private boolean isFirstBanner = true;

    private void getBannerData() {
        if (loading.getVisibility() == View.VISIBLE) {
            loading.setVisibility(View.GONE);
        }
        if (loading != null && loading.getVisibility() == View.GONE && isFirstBanner) {
            loading.setVisibility(View.VISIBLE);
            animation.start();
        }
        RequestParams params = new RequestParams();
        if (homebanner == null || flag || CommonUtil.checkNetState(context)) {
            AddClient.get(Address.INDEXBANNER, params, new AsyncHttpResponseHandler() {
                @Override
                public void onSuccess(int statusCode, String content) {
                    isFirstBanner = false;
                    if (ptrgv.getVisibility() == View.GONE) {
                        ptrgv.setVisibility(View.VISIBLE);
                    }
                    try {
                        if (!TextUtils.isEmpty(content)) {
                            try {
                                homebanner = JSON.parseObject(content, HomeBannerEntity.class);
                                SharePrefUtil.saveObj(context, "homebanner", homebanner); // 缓存数据

                            } catch (Exception e) {
                            }
                            List<HomeBanner> list = homebanner.getArray();
                            prepareViewPage(context, list);
                            // getJingData(currentPage1, 0);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onFailure(Throwable arg0, String arg1) {
                    ptrgv.onRefreshComplete();
                    if (isFirstBanner) {
                        animation.stop();
                        // loading.setVisibility(View.VISIBLE);
                        imageView.setVisibility(View.GONE);
                        load_fail.setVisibility(View.VISIBLE);
                        load_fail.setOnClickListener(new OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                load_fail.setVisibility(View.GONE);
                                getBannerData();
                                getJingData(currentPage1, 0);
                                imageView.setVisibility(View.VISIBLE);
                                animation.start();
                            }
                        });
                    }
                }
            });
        } else {
            ptrgv.onRefreshComplete();
            if (isFirstBanner) {
                animation.stop();
                // loading.setVisibility(View.VISIBLE);
                imageView.setVisibility(View.GONE);
                load_fail.setVisibility(View.VISIBLE);
                load_fail.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        load_fail.setVisibility(View.GONE);
                        getBannerData();
                        getJingData(currentPage1, 0);
                        imageView.setVisibility(View.VISIBLE);
                        animation.start();
                    }
                });
            }
        }
    }

    private HomeListAdapter mAdapter = null;
    private final LinkedList<HomeData> mInfos = new LinkedList<HomeData>();
    private boolean flag2 = false;
    private boolean isFirstJing = true;

    private void getJingData(final int currentPage, final int loadType) {
        if (!CommonUtil.checkNetState(context)) { // 判断是否连接网络，给用户提示
            Toast.makeText(context, R.string.pLease_check_network, 0).show();
        }
        loading.setVisibility(View.GONE);
        if (loading != null && loading.getVisibility() == View.GONE && isFirstJing) {
            loading.setVisibility(View.VISIBLE);
            animation.start();
        }
        RequestParams params = new RequestParams();
        params.put("uid", UserState.getUserUid());
        params.put("page", String.valueOf(currentPage));
        params.put("pagesize", "16");
        if (entity == null || flag2 || CommonUtil.checkNetState(context)) {
            AddClient.get(Address.MAINJING, params, new AsyncHttpResponseHandler() {
                @Override
                public void onSuccess(int statusCode, String content) {
                    isFirstJing = false;
                    ptrgv.onRefreshComplete();
                    if (ptrgv.getVisibility() == View.GONE) {
                        ptrgv.setVisibility(View.VISIBLE);
                    }
                    if (loading.getVisibility() == View.VISIBLE) {
                        animation.stop();
                        loading.setVisibility(View.GONE);
                    }
                    if (ptrgv.getVisibility() == View.GONE) {
                        ptrgv.setVisibility(View.VISIBLE);
                    }
                    if (!TextUtils.isEmpty(content)) {
                        try {
                            entity = JSON.parseObject(content, HomeEntity.class);
                            if (null == entity) {
                                Toast.makeText(context, "获取数据失败,请重新获取", 0).show();
                                return;
                            }
                            List<HomeData> list = entity.getArray();
                            if (list.size() == 0) {
                                Toast.makeText(context, "获取数据失败,请重新获取", 0).show();
                                return;
                            }
                            if (loadType == 0) {// 说明是上拉

                                if (mAdapter == null) {
                                    mAdapter = new HomeListAdapter(context, mInfos);
                                    ptrgv.getRefreshableView().setAdapter(mAdapter);
                                    mAdapter.notifyDataSetChanged();
                                }
                                SharePrefUtil.saveObj(context, "jinghua", entity); // 缓存主题数据

                                mAdapter.clearItems();
                                mAdapter.addItemTop(list);
                                mAdapter.notifyDataSetChanged();
                            } else if (loadType == 1) {
                                if (mAdapter == null) {
                                    mAdapter = new HomeListAdapter(context, mInfos);
                                }
                                mAdapter.addItemLast(list);
                                mAdapter.notifyDataSetChanged();
                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }
                }

                @Override
                public void onFailure(Throwable arg0, String arg1) {
                    ptrgv.onRefreshComplete();
                    if (isFirstJing) {
                        animation.stop();
                        loading.setVisibility(View.VISIBLE);
                        imageView.setVisibility(View.GONE);
                        load_fail.setVisibility(View.VISIBLE);
                        load_fail.setOnClickListener(new OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                load_fail.setVisibility(View.GONE);
                                getBannerData();
                                getJingData(currentPage1, 0);
                                imageView.setVisibility(View.VISIBLE);
                                animation.start();
                            }
                        });
                    }
                }
            });
        } else {
            if (isFirstJing) {
                animation.stop();
                loading.setVisibility(View.VISIBLE);
                imageView.setVisibility(View.GONE);
                load_fail.setVisibility(View.VISIBLE);
                load_fail.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        load_fail.setVisibility(View.GONE);
                        getBannerData();
                        getJingData(currentPage1, 0);
                        imageView.setVisibility(View.VISIBLE);
                        animation.start();
                    }
                });
            }
        }
    }

    // private List<HomeBanner> list;

    private ArrayList<View> dotLists;
    private RollViewPager rollViewPager;

    public void prepareViewPage(final Context context, final List<HomeBanner> list) {
        List<String> titleList = new ArrayList<String>();
        List<String> imageUrlList = new ArrayList<String>();
        for (HomeBanner homeBanner : list) {
            titleList.add(homeBanner.getTitle());
            imageUrlList.add(homeBanner.getCoverpath());
        }
        initDots(list.size());
        rollViewPager =
                new RollViewPager(context, dotLists, R.drawable.point_normal,
                        R.drawable.point_enable, new RollViewPager.MyOnTouchCllickCallBack() {
                            @Override
                            public void OnTouchCllick(int position) {
                                String type = list.get(position % list.size()).getType();
                                if (type.equals("web")) {// 跳转到详情
                                    Intent intent1 =
                                            new Intent(context, HomeBannerDetailActivity.class);
                                    intent1.putExtra("url", list.get(position % list.size())
                                            .getLink());
                                    context.startActivity(intent1);
                                    getActivity().overridePendingTransition(
                                            R.anim.new_dync_in_from_right,
                                            R.anim.new_dync_out_to_left);
                                } else if (type.equals("appthread")) {// 跳转到帖子详情
                                    Intent intent2 = new Intent(context, PostDetailActivity.class);
                                    intent2.putExtra(Constants.KEY_POST_TID,
                                            list.get(position % list.size()).getLink());
                                    context.startActivity(intent2);
                                    getActivity().overridePendingTransition(
                                            R.anim.new_dync_in_from_right,
                                            R.anim.new_dync_out_to_left);
                                }
                            }
                        });
        rollViewPager.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,
                LayoutParams.WRAP_CONTENT));
        rollViewPager.setTitle(tvDescription, titleList);
        rollViewPager.setImageUrl(imageUrlList);
        rollViewPager.startRoll();
        mViewPager.removeAllViews();
        mViewPager.addView(rollViewPager);
    }

    private void initDots(int size) {
        dotLists = new ArrayList<View>();
        llPoints.removeAllViews();
        for (int i = 0; i < size; i++) {
            LinearLayout.LayoutParams layoutParams =
                    new LinearLayout.LayoutParams(CommonUtil.dip2px(context, 10),
                            CommonUtil.dip2px(context, 10));
            layoutParams.setMargins(5, 0, 5, 0);
            // LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(15,
            // 15);

            // lp.leftMargin = 10;

            View m = new View(context);
            if (i == 0) {
                m.setBackgroundResource(R.drawable.point_enable);
            } else {
                m.setBackgroundResource(R.drawable.point_normal);
            }
            m.setLayoutParams(layoutParams);
            dotLists.add(m);
            llPoints.addView(m);
        }
    }

    private MyHuiFu huifu;
    private MainNewAdapter newadapter;
    private boolean flag3 = false;
    private boolean isFirstNew = true;

    // loadType 0为刷新 1为下拉

    private void getNewData(int currentPage2, final int loadType) {
        if (loading.getVisibility() == View.VISIBLE) {
            loading.setVisibility(View.GONE);
        }
        if (loading != null && loading.getVisibility() == View.GONE && isFirstNew) {
            loading.setVisibility(View.VISIBLE);
            animation.start();
        }
        RequestParams params = new RequestParams();
        params.put("page", String.valueOf(currentPage2));
        params.put("pagesize", Address.PAGECOMMONSIZE);
        if (huifu == null || flag3 || CommonUtil.checkNetState(context)) {
            AddClient.get(Address.MAINNEW, params, new AsyncHttpResponseHandler() {
                @Override
                public void onSuccess(int statusCode, String content) {
                    isFirstNew = false;
                    if (loading != null && loading.getVisibility() == View.VISIBLE) {
                        animation.stop();
                        loading.setVisibility(View.GONE);
                    }
                    ptrgv.getRefreshableView().setColumnCount(1);
                    try {
                        huifu = JSON.parseObject(content, MyHuiFu.class);
                        SharePrefUtil.saveObj(context, "huifu", huifu); // 缓存数据

                        List<Message> array = huifu.getArray();
                        if (loadType == 0) {
                            SharePrefUtil.saveObj(context, "huifu", huifu); // 缓存数据

                            if (newadapter != null) {
                                newadapter.clearItems();
                                newadapter.addItems(array);
                                newadapter.notifyDataSetChanged();
                            } else {
                                newadapter = new MainNewAdapter(context);
                                newadapter.addItems(array);
                                ptrgv.getRefreshableView().setAdapter(newadapter);
                                newadapter.notifyDataSetChanged();
                            }
                        } else if (loadType == 1) {
                            newadapter.addItems(array);
                            newadapter.notifyDataSetChanged();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    super.onSuccess(statusCode, content);
                }

                @Override
                public void onFailure(Throwable error, String content) {
                    ptrgv.onRefreshComplete();
                    if (isFirstNew) {
                        animation.stop();
                        loading.setVisibility(View.VISIBLE);
                        imageView.setVisibility(View.GONE);
                        load_fail.setVisibility(View.VISIBLE);
                        load_fail.setOnClickListener(new OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                load_fail.setVisibility(View.GONE);
                                getNewData(1, 0);
                                imageView.setVisibility(View.VISIBLE);
                                animation.start();
                            }
                        });
                    }
                    super.onFailure(error, content);
                }
            });
        } else {
            if (loading != null && loading.getVisibility() == View.VISIBLE) {
                animation.stop();
                loading.setVisibility(View.GONE);
            }
            flag3 = true;
            ptrgv.getRefreshableView().setColumnCount(1);
            List<Message> array = huifu.getArray();
            if (newadapter == null) {
                newadapter = new MainNewAdapter(context);
                newadapter.addItems(array);
                ptrgv.getRefreshableView().setAdapter(newadapter);
                newadapter.notifyDataSetChanged();
            } else {
                newadapter.notifyDataSetChanged();
            }
        }
    }

    private HomeVideoAdapter videoAdapter;
    private int total3;
    private HomeVideo video;
    private boolean flag4 = false;
    private boolean isFirstVideo = true;

    private void loadVideoData(int videopage2) {
        loading.setVisibility(View.GONE);
        if (loading != null && loading.getVisibility() == View.GONE && isFirstVideo) {
            animation.start();
            loading.setVisibility(View.VISIBLE);
        }
        RequestParams params = new RequestParams();
        params.put("page", String.valueOf(videopage2));
        params.put("pagesize", "10");
        params.put("filter", "petvideo");
        if (video == null || flag4 || CommonUtil.checkNetState(context)) {
            AddClient.get(Address.MAINNEW, params, new AsyncHttpResponseHandler() {
                @Override
                public void onSuccess(int statusCode, String content) {
                    isFirstVideo = false;
                    ptrgv.getRefreshableView().setColumnCount(1);
                    if (loading != null && loading.getVisibility() == View.VISIBLE) {
                        animation.stop();
                        loading.setVisibility(View.GONE);
                    }
                    try {
                        video = JSON.parseObject(content, HomeVideo.class);
                        SharePrefUtil.saveObj(context, "video", video); // 缓存数据
                        List<Video> array = video.array;
                        if (videoAdapter == null) {
                            videoAdapter = new HomeVideoAdapter(array, context);
                            ptrgv.getRefreshableView().setAdapter(videoAdapter);
                            videoAdapter.notifyDataSetChanged();
                        } else {
                            if (null != array && array.size() > 0) {
                                videoAdapter.addItems(array);
                            }
                        }
                        total3 = Integer.valueOf(video.getTotal());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    super.onSuccess(statusCode, content);
                }

                @Override
                public void onFailure(Throwable error, String content) {
                    ptrgv.onRefreshComplete();
                    if (isFirstVideo) {
                        animation.stop();
                        loading.setVisibility(View.VISIBLE);
                        imageView.setVisibility(View.GONE);
                        load_fail.setVisibility(View.VISIBLE);
                        load_fail.setOnClickListener(new OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                load_fail.setVisibility(View.GONE);
                                loadVideoData(1);
                                imageView.setVisibility(View.VISIBLE);
                                animation.start();
                            }
                        });
                    }
                    super.onFailure(error, content);
                }
            });
        } else {
            if (isFirstVideo) {
                animation.stop();
                loading.setVisibility(View.VISIBLE);
                imageView.setVisibility(View.GONE);
                load_fail.setVisibility(View.VISIBLE);
                load_fail.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        load_fail.setVisibility(View.GONE);
                        loadVideoData(1);
                        imageView.setVisibility(View.VISIBLE);
                        animation.start();
                    }
                });
            }
        }
    }

    private int tab = 1;

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.main_leftmenu:
                menu.toggle();
                break;
            case R.id.main_rightmenu:
                break;
            case R.id.main_search:
                break;
            case R.id.club_jinghua:
                gc();
                ptrgv.getRefreshableView().getFooterView().setVisibility(View.VISIBLE);
                club_jinghua.setSelected(true);
                club_new.setSelected(false);
                club_video.setSelected(false);
                top_jinghua.setSelected(true);
                top_new.setSelected(false);
                top_video.setSelected(false);
                ptrgv.setMode(PullToRefreshBase.Mode.BOTH);
                tab = 1;
                if (mAdapter == null) {
                    getJingData(1, 0);
                } else {
                    ptrgv.getRefreshableView().setAdapter(mAdapter);
                    ptrgv.getRefreshableView().setColumnCount(2);
                }
                break;
            case R.id.club_new:
                gc();
                ptrgv.getRefreshableView().getFooterView().setVisibility(View.VISIBLE);
                club_jinghua.setSelected(false);
                club_new.setSelected(true);
                club_video.setSelected(false);
                top_jinghua.setSelected(false);
                top_new.setSelected(true);
                top_video.setSelected(false);
                ptrgv.setMode(PullToRefreshBase.Mode.BOTH);
                tab = 2;
                if (newadapter == null) {
                    getNewData(currentPage2, 0);
                } else {
                    ptrgv.getRefreshableView().setAdapter(newadapter);
                    ptrgv.getRefreshableView().setColumnCount(1);
                }
                break;
            case R.id.club_video:
                gc();
                tab = 3;
                ptrgv.getRefreshableView().getFooterView().setVisibility(View.GONE);
                club_jinghua.setSelected(false);
                club_new.setSelected(false);
                club_video.setSelected(true);
                top_jinghua.setSelected(false);
                top_new.setSelected(false);
                top_video.setSelected(true);
                ptrgv.setMode(PullToRefreshBase.Mode.BOTH);
                if (videoAdapter == null) {
                    loadVideoData(1);
                } else {
                    ptrgv.getRefreshableView().setAdapter(videoAdapter);
                    ptrgv.getRefreshableView().setColumnCount(1);
                }
                break;
            case R.id.top_jinghua:
                gc();
                ptrgv.getRefreshableView().getFooterView().setVisibility(View.VISIBLE);
                club_jinghua.setSelected(true);
                club_new.setSelected(false);
                club_video.setSelected(false);
                top_jinghua.setSelected(true);
                top_new.setSelected(false);
                top_video.setSelected(false);
                ptrgv.setMode(PullToRefreshBase.Mode.BOTH);
                tab = 1;
                if (mAdapter == null) {
                    getJingData(1, 0);
                } else {
                    ptrgv.getRefreshableView().setColumnCount(2);
                    ptrgv.getRefreshableView().setAdapter(mAdapter);
                }
                top_check.setVisibility(View.GONE);
                break;
            case R.id.top_new:
                gc();
                ptrgv.getRefreshableView().getFooterView().setVisibility(View.VISIBLE);
                club_jinghua.setSelected(false);
                club_new.setSelected(true);
                club_video.setSelected(false);
                top_jinghua.setSelected(false);
                top_new.setSelected(true);
                top_video.setSelected(false);
                ptrgv.setMode(PullToRefreshBase.Mode.BOTH);
                tab = 2;
                if (newadapter == null) {
                    getNewData(currentPage2, 0);
                } else {
                    ptrgv.getRefreshableView().setAdapter(newadapter);
                    ptrgv.getRefreshableView().setColumnCount(1);
                }
                top_check.setVisibility(View.GONE);
                break;
            case R.id.top_video:
                gc();
                tab = 3;
                ptrgv.getRefreshableView().getFooterView().setVisibility(View.GONE);
                club_jinghua.setSelected(false);
                club_new.setSelected(false);
                club_video.setSelected(true);
                top_jinghua.setSelected(false);
                top_new.setSelected(false);
                top_video.setSelected(true);
                ptrgv.setMode(PullToRefreshBase.Mode.BOTH);
                if (videoAdapter == null) {
                    loadVideoData(1);
                } else {
                    ptrgv.getRefreshableView().setAdapter(videoAdapter);
                    ptrgv.getRefreshableView().setColumnCount(1);
                }
                top_check.setVisibility(View.GONE);
                break;
            case R.id.back_top:
                top_check.setVisibility(View.GONE);
                switch (tab) {
                    case 1:
                        if (mAdapter != null) {
                            ptrgv.getRefreshableView().setColumnCount(2);
                            ptrgv.getRefreshableView().setAdapter(mAdapter);
                        }
                        break;
                    case 2:
                        if (newadapter != null) {
                            ptrgv.getRefreshableView().setAdapter(newadapter);
                            ptrgv.getRefreshableView().setColumnCount(1);
                        }
                        break;
                    case 3:
                        if (videoAdapter != null) {
                            ptrgv.getRefreshableView().setAdapter(videoAdapter);
                            ptrgv.getRefreshableView().setColumnCount(1);
                        }
                        break;

                    default:

                        break;
                }
                if (back_top.getVisibility() == View.VISIBLE) {
                    back_top.setVisibility(View.GONE);
                }

        }
    }

    private void gc() {
        if (back_top.getVisibility() == View.VISIBLE) {
            back_top.setVisibility(View.GONE);
        }
        System.gc();
        ptrgv.getRefreshableView().loadlock = false;
    }

    public static void openRight() {
        menu.showSecondaryMenu();
    }

    /** 弹出dialog */
    private void showEnterDialog(String title) {
        SimpleDateFormat sdf = new SimpleDateFormat("dd");
        String date = UserState.getUserUid() + sdf.format(new java.util.Date());
        if (UserState.isLogged()) {
            if (!(UserState.getUserUid() + date).equals(sp.getString("date", null))) {
                // 提示加分
                RequestParams params = new RequestParams();
                XDHttpClient.post(xdConfig.LOGINSIGN, params, new AsyncHttpResponseHandler() {

                    @Override
                    public void onSuccess(int statusCode, String content) {
                        super.onSuccess(statusCode, content);
                        JSONObject jsonObj;
                        try {
                            jsonObj = new JSONObject(content);
                            String score = jsonObj.getString("niuniu");
                            if (!score.equals("")) {
                                showDialog2(score);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(Throwable error, String content) {
                        super.onFailure(error, content);
                    }
                });
            }

        }
        Editor editor = sp.edit();
        editor.putString("date", date);
        editor.commit();
    }

    private void showDialog2(String str) {
        LayoutInflater inflater = getLayoutInflater(getArguments());
        View layout = inflater.inflate(R.layout.dialog_two, null);
        TextView tv_addscore = (TextView) layout.findViewById(R.id.tv_addscore);
        tv_addscore.setText(str);
        Toast toast = new Toast(context);
        toast.setGravity(Gravity.CENTER, 0, 0);
        toast.setDuration(Toast.LENGTH_LONG);
        toast.setView(layout);
        toast.show();
    }

    @Override
    public void onResume() {
        super.onResume();
        // if (null != rollViewPager) {
        // rollViewPager.startRoll();
        // }
        showEnterDialog("6");
    }

    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        context.unregisterReceiver(mChangeReceiver);
    }

    //
    class ConnectionChangeReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {


            if (CommonUtil.isNetworkAvailable(context) == 0) {
                // unconnect network
                Toast.makeText(context, "网络断开连接，请检查网络......", Toast.LENGTH_LONG).show();
            } else {
                // Toast.makeText(context, "网络连接上了", Toast.LENGTH_LONG).show();
                // refresh data
                load_fail.setVisibility(View.GONE);
                getBannerData();
                getJingData(currentPage1, 0);
                imageView.setVisibility(View.VISIBLE);
                animation.start();
            }
        }
    }

}
